package controllers;

import java.util.*;

import models.*;
import play.data.validation.*;
import play.mvc.*;

public class Retailer extends ConnectedUser {
	
    public static void index() {
        members();
    }
	
    public static void members() {
        render();
    }
    
    public static void discounts() {
    	renderDiscounts();
    }
    
    public static void profile() {
        render();
    }
    
    public static void profileEditInfo() {
	render();
    }
    
    public static void profileChangePwd() {
	render();
    }
    
    public static void  changeInfo(String retailName, String email, String desc) {
	String userId = session.get("logged");
	User user = null;

	if(userId != null) {
	    try{
		user = User.findById(Long.parseLong(userId));
	    }catch (Exception e){
		e.printStackTrace();
	    }
	}
	
	if (user!=null) {
	    RetailUser retailUser = (RetailUser) user;
	    retailUser.name = retailName;
	    retailUser.email = email;
	    retailUser.desc = desc;
	    retailUser.save();
	    flash.success("Your information has been successfully changed!");
	    profile();
	}
    }
    
    public static void changePwd(String oldPwd, String newPwd1, String newPwd2) {
	String userId = session.get("logged");
	User user = null;

	if(userId != null) {
	    try{
		user = User.findById(Long.parseLong(userId));
	    }catch (Exception e){
		e.printStackTrace();
	    }
	}
	
	if (user == null || !user.checkPassword(oldPwd)) {
	    flash.error("Bad password");
	    profileChangePwd();
	}else {
	    if (newPwd1.equals(newPwd2)) {
		user.password = newPwd1;
		user.save();
		flash.success("Password has been successfully changed!");
		profile();
	    }else {
		flash.error("Please input again");
		profileChangePwd();
	    }
	}
    }
    
    public static void findClubMembers(@Required String name) {
    	
    	if(validation.hasErrors()) {
    		flash.error("Please type name of the member");
    		members();
    	}
    	
    	List<ClubUser> clubs = connectedUser.getActivePartners();
    	List<Member> members = Member.findActiveMembersByNameAndClubs(name, clubs);
    	
    	if(members.size() == 0) {
    		renderArgs.put("notice", "No results for '" + name + "'");
    	}
    	
    	render(members);
    }
}
